const fs = require('fs');
const path = require('path');
const toPath = __dirname

class SuperTask {
    maxCount = 0;
    taskList = [];
    runningCount = 0;

    constructor(maxCount = 2) {
        this.maxCount = maxCount
    }

    taskLength = 0

    addTask(task) {
        this.taskList.push(task)
        this.taskLength = this.taskList.length
    }

    addTasks(tasks) {
        tasks.forEach(i => {
            this.addTask(i)
        })
    }

    errorList = []

    doTask() {
        while (this.runningCount < this.maxCount && this.taskList.length) {
            const task = this.taskList.shift()
            this.runningCount++
            task().then((res) => {
                // console.log(`${this.taskLength-this.taskList.length}/${this.taskLength}:ok`)
                // console.log(res)
            }).catch(e => {
                console.log(`${this.taskLength-this.taskList.length}/${this.taskLength}:error`)
                console.log(e)
                this.errorList.push(e)
            }).finally(() => {
                this.runningCount--
                this.doTask()
            })
        }
        if (!this.taskList.length && this.runningCount === 0) {
            this._done && this._done(this.errorList)
            console.log(this.errorList)
            fs.writeFileSync(path.resolve(toPath, 'transform.txt'), JSON.stringify(this.errorList, '', 2))
        }
        return this
    }

    _done = null

    done(cb) {
        if (cb) {
            this._done = cb
        }
    }
}

module.exports = SuperTask

/*
function createTask(file){
    return function (){
        return new Promise( (resolve,reject)=>{

        })
    }
}

const superTask = new SuperTask(10)
const taskList = videoFileListWithWorkDir.map(i=>createTask(i))
superTask.addTasks(taskList)
superTask.doTask().done(()=>{
    console.log('转换完成')
})*/
